package com.aynu.admin.utils.admin;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.signers.JWTSigner;
import cn.hutool.jwt.signers.JWTSignerUtil;
import com.aynu.admin.config.JWTProperties;
import org.springframework.stereotype.Component;

import java.security.KeyPair;
import java.util.Date;

@Component
public class JWTTool {
    private final JWTProperties jwtProperties;
    private final JWTSigner jwtSigner;
    private static final int EXPIRE = 0;
    public JWTTool(KeyPair keyPair, JWTProperties jwtProperties) {
        this.jwtSigner= JWTSignerUtil.createSigner("rs256",keyPair);
        this.jwtProperties = jwtProperties;
    }

    //Generate a token based on the user alias and token lifetime
    public String createToken(String user){
        return JWT.create()
                .setPayload("user",user)
                .setExpiresAt(new Date(System.currentTimeMillis()+jwtProperties.getTokenLifetime().toMillis()))
                .setSigner(jwtSigner)
                .sign();
    }
    public boolean isValid(String token){

         if(JWTUtil.verify(token, jwtSigner)){
             String exp = getPayload(token, "exp");
             String now= String.valueOf(System.currentTimeMillis());
             return exp.compareTo(now)>EXPIRE;
         }
         return false;
    }
    public String getPayload(String token,String key){
        return JWTUtil.parseToken(token).getPayload(key).toString();
    }

}